package com.sheliduan.itlearning.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.sheliduan.itlearning.common.domain.dos.UserDO;
import com.sheliduan.itlearning.common.domain.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;

/**
 * @author: 断舍离
 * @date: 2025/2/3 10:48
 * @description: token工具类
 **/
@Component
public class TokenUtil {

    private static UserMapper staticUserMapper;

    @Autowired
    private UserMapper userMapper;

    @PostConstruct
    public void setStaticUserMapper(){
        staticUserMapper = userMapper;
    }

    /*
    * 生成token
    * */
    public static String generateToken(String userId, String password){
        // 获取表示当前日期的日历类
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        // 将该日历类表示的事件向后推移1周
        calendar.add(Calendar.WEEK_OF_YEAR, 1);
        return JWT.create().withAudience(userId) //将userId保存到token中
                .withExpiresAt(calendar.getTime()) // 1周后token过期
                .sign(Algorithm.HMAC256(password)); // 以用户密码作为token密钥
    }

    /*
    * 根据token获取当前登录的用户
    * */
    public static UserDO getCurrentUser(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if(token != null) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserMapper.selectById(Integer.valueOf(userId));
            }
        } catch (Exception e){
            return null;
        }
        return null;
    }
}
